package com.mdd.filter;

import com.alibaba.fastjson.JSON;
import com.mdd.common.BaseContext;
import com.mdd.common.R;
import lombok.extern.slf4j.Slf4j;
import org.springframework.util.AntPathMatcher;

import javax.servlet.*;
import javax.servlet.annotation.WebFilter;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
@Slf4j
@WebFilter(urlPatterns = "/*")
public class LoginCheckFilter implements Filter {
    //url匹配器
    private static final AntPathMatcher PATH_MATCHER =  new AntPathMatcher();

    @Override
    public void doFilter(ServletRequest servletRequest, ServletResponse servletResponse, FilterChain filterChain) throws IOException, ServletException {
        HttpServletRequest httpServletRequest = (HttpServletRequest)servletRequest;
        HttpServletResponse httpServletResponse = (HttpServletResponse) servletResponse;
        //获取请求uri
        String url = httpServletRequest.getRequestURI();

        log.info("拦截的请求:"+url);
        //定义不需要处理的请求
        String[] urls = new String[]{
                "/employee/login",
                "/employee/logout",
                "/backend/**",
                "/common/**",
                "/front/**",
                "/user/sendMsg",
                "/user/login",
                "/doc.html",
                "/webjars/**",
                "/swagger-resources",
                "/v2/api-docs"
        };

        //匹配该请求是否为不需要处理的请求
        if (matchUrl(urls,url)) {
            filterChain.doFilter(httpServletRequest,httpServletResponse);
            return;
        }
        //获取Session检验是否有用户登录信息
        Object employee = httpServletRequest.getSession().getAttribute("employee");
        if (employee != null) {
            BaseContext.setCurrentId((Long) employee);
            filterChain.doFilter(httpServletRequest,httpServletResponse);
            return;
        }

        //获取Session检验是否有客户端用户登录信息
        Object user = httpServletRequest.getSession().getAttribute("user");
        if (user != null) {
            BaseContext.setCurrentId((Long) user);
            filterChain.doFilter(httpServletRequest,httpServletResponse);
            return;
        }
        //未登录返回未登录结果，通过流的方式向前端发送json数据.
        httpServletResponse.getWriter().write(JSON.toJSONString(R.error("NOTLOGIN")));
    }

    /**
     * 匹配请求
     * @param urls
     * @param url
     * @return
     */
    private boolean matchUrl(String[] urls,String url){
        for (String s : urls) {
            if (PATH_MATCHER.match(s,url)) {
                return true;
            }
        }
        return false;
    }
}
